<?php
/**
 * Category
 *
 * PHP version 5
 *
 * @category Controller
 * @version  1.0
 * @author   Duonght <hduongdmit@gmail.com>
 */
App::uses('AppController', 'Controller');
class CategorysController extends AppController {

	/**
	* Components
	* @var array
	*/
	public $components = array('Common' ,'Paginator');
	public $uses = 'Category';
	private $categorymulti = array();
	private $stt = -1;

	public function beforeFilter(){
		parent::beforeFilter();
		$category_type = Configure::read('category_type');
		$this->set('category_type', $category_type);
	}

	/**
	 * Show category
	 */
	public function index(){
		//get param filter
		$conditions = array('cat_active' => 1);
		if ($this->request->query) {
			$cat_type = $this->request->query['cat_type'];
			if(!empty($cat_type)){
				$conditions['cat_type'] = $cat_type;
			}
		}

		$paginate = array(
				'fields' => 'id,cat_name,cat_order,cat_home,cat_type,cat_description,cat_parent_id,cat_has_child,cat_level',
				//'limit' => ConstAdminComponent::PAGE_NUMBER_LIMIT,
				'conditions' => $conditions,
				'order' => array(
					'cat_type' => 'asc',
					'cat_order' => 'asc',
				),
		);

		$this->Paginator->settings = $paginate;
		$listCategory = $this->Paginator->paginate('Category');
		$categories = array();
		foreach ($listCategory as $key => $category){
			$categorys = $category['Category'];
			$categories[$categorys['cat_parent_id']][$categorys['id']] = $categorys;
		}

		$this->_sortLevel($categories);
		//forward to view layout
		$this->set(array(
				'datas' => $this->categorymulti,
				//'page_number_limit' => ConstAdminComponent::PAGE_NUMBER_LIMIT,
				'title_for_layout' => $this->moduleAdmin['categorys']['index'],
		));

	}

	/**
	 * Add new category
	 */
	public function add(){
		if ($this->request->is('post')) {
			$params = $this->request->data;
			$this->Category->create();

			$cat_rewrite = CommonComponent::rewriteTitle($params['Category']['cat_name']);
			$params['Category']['cat_rewrite'] = $cat_rewrite;
			$params['Category']['cat_md5'] = md5(md5($cat_rewrite).Configure::read('Security.salt'));

			$parent_rewrite = $this->Category->getCatRewriteByParentId($params['Category']['cat_parent_id']);
			$params['Category']['cat_parent_rewrite'] = $parent_rewrite;

			$cat_level = $this->Category->getLevelCategoryParent($params['Category']['cat_parent_id']);
			$params['Category']['cat_level'] = $cat_level + 1;

			if ($this->Category->save($params)) {
				$this->Session->setFlash(__('Success'), 'success');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('Save could not be saved. Please, try again'), 'error');
			}
		}

		//forge view
		$this->set('title_for_layout', $this->moduleAdmin['categorys']['add']);
	}

	/**
	 * Edit category
	 *
	 * @param string $id
	 */
	public function edit($id = null){
		if (!$id) {
			throw new NotFoundException(__('Invalid post'));
		}

		//get detail
		$detail = $this->Category->findById($id);
		if (!$detail) {
			throw new NotFoundException(__('Invalid post'));
		}

		//get category parent
		$listCategory = $this->Category->getListCategoryType("'" . $detail['Category']['cat_type'] . "'");
		$categories = array();
		foreach ($listCategory as $key => $category){
			$categorys = $category['categories_multi'];
			$categories[$categorys['cat_parent_id']][$categorys['id']] = $categorys;
		}

		$this->_sortLevel($categories);

		//set view
		$this->set('detail', $detail);
		$this->set('listCategory', $this->categorymulti);
		//edit
		if ($this->request->is('post')) {
			$params = $this->request->data;
			$cat_rewrite = CommonComponent::rewriteTitle($params['Category']['cat_name']);
			$params['Category']['cat_rewrite'] = $cat_rewrite;
			$params['Category']['cat_md5'] = md5(md5($cat_rewrite).Configure::read('Security.salt'));

			$parent_rewrite = $this->Category->getCatRewriteByParentId($params['Category']['cat_parent_id']);
			$params['Category']['cat_parent_rewrite'] = $parent_rewrite;

			$this->Category->id = $id;
			if ($this->Category->save($params)) {
				$this->Session->setFlash(__('Updated success.'), 'success');
// 				$log = $this->Category->getDataSource()->getLog(false, false);
// 				debug($log);
// 				die;
				return $this->redirect(array('action' => 'index'));
			}

		}
		$this->set('title_for_layout', $this->moduleAdmin['categorys']['edit']);
	}

	/**
	 * Delete category
	 *
	 * @param string $id
	 */
	public function delete($id = null){
		$this->layout = null;
		if ($this->request->is('get')) {
			throw new MethodNotAllowedException();
		}

		$this->Category->read('id', $id);
		$this->Category->set('cat_active', 0);
		$this->Category->save();
		$this->Session->setFlash(__('Delete success'), 'success');
		return $this->redirect(array('action' => 'index'));

	}

	/**
	 * Update news
	 * @param string $id
	 * @param string $type
	 */
	public function update($id = null, $field = 'cat_home'){
		$this->layout = null;
		$this->render(false);
		if ($this->request->is('post')) {
			$value = $this->request->data['value'];
			$this->Category->set('id', $id);
			$this->Category->set($field, $value);
			$this->Category->save();
			echo $value;
		}
	}

	/**
	 * Ajax lay danh muc theo category type
	 */
	public function getCategoryType(){
		$this->layout = null;
		if ($this->request->is('post')) {
			$params = $this->request->data;
			$cat_type = $params['cat_type'];
			$listCategory = $this->Category->getListCategoryType("'" . $cat_type . "'");

			$categories = array();
			foreach ($listCategory as $key => $category){
				$categorys = $category['categories_multi'];
				$categories[$categorys['cat_parent_id']][$categorys['id']] = $categorys;
			}

			$this->_sortLevel($categories);
		}

		$this->set('listCategory', $this->categorymulti);
		$this->render('category_type');
	}

	/**
	 * Sap xep danh muc theo level
	 *
	 * @param array $arrayCategory
	 * @param number $keystart nút cha
	 * @param number $level
	 */
	private function _sortLevel($arrayCategory, $keystart = 0, $level = -1){
		//kiểm tra xem tồn tại record không
		if (array_key_exists($keystart, $arrayCategory)) {
			$level++;
			foreach ($arrayCategory[$keystart] as $key => $value){

				//gán các phần tử cho array menu sắp xếp theo đúng vị trí
				//tang so thu tu
				$this->stt++;
				$this->categorymulti[$this->stt] = $value;

				//gan level cho menu
				$this->categorymulti[$this->stt]['level'] = $level;

				//thiet lap de biet day la` 1 nut cha
				if (array_key_exists($key,$arrayCategory)){
					$this->categorymulti[$this->stt]["parent"] = 1;
				} else {
					$this->categorymulti[$this->stt]["parent"] = 0;
				}

				//de quy de lap lai, neu menu_id nam trong array cac menu cha
				$this->_sortLevel($arrayCategory, $key, $level);
			}
		}
	}

}
